package com.atguigu.examsystemserver.service.impl;


import com.atguigu.examsystemserver.entity.AnswerRecord;
import com.atguigu.examsystemserver.entity.ExamRecord;
import com.atguigu.examsystemserver.entity.Paper;
import com.atguigu.examsystemserver.entity.Question;
import com.atguigu.examsystemserver.exception.ExamException;
import com.atguigu.examsystemserver.mapper.AnswerRecordMapper;
import com.atguigu.examsystemserver.mapper.ExamRecordMapper;
import com.atguigu.examsystemserver.service.AIService;
import com.atguigu.examsystemserver.service.AnswerRecordSercive;
import com.atguigu.examsystemserver.service.ExamRecordService;
import com.atguigu.examsystemserver.service.PaperService;
import com.atguigu.examsystemserver.vo.ExamRankingVO;
import com.atguigu.examsystemserver.vo.GradingResult;
import com.atguigu.examsystemserver.vo.StartExamVo;
import com.atguigu.examsystemserver.vo.SubmitAnswerVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 考试记录Service实现类
 * 实现考试记录相关的业务逻辑
 */
@Service
public class ExamRecordServiceImpl extends ServiceImpl<ExamRecordMapper, ExamRecord> implements ExamRecordService {


    @Autowired
    PaperService paperService;

    @Autowired
    AnswerRecordSercive answerRecordSercive;

    @Autowired
    AnswerRecordMapper answerRecordMapper;

    @Autowired
    AIService aiService;

    @Override
    public ExamRecord startExamRecord(StartExamVo startExamVo) {
        LambdaQueryWrapper<ExamRecord> examRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        examRecordLambdaQueryWrapper.eq(ExamRecord::getStudentName, startExamVo.getStudentName())
                .eq(ExamRecord::getExamId, startExamVo.getPaperId())
                .eq(ExamRecord::getStatus, "进行中");
        ExamRecord examRecord = baseMapper.selectOne(examRecordLambdaQueryWrapper);
        if (examRecord == null) {
            examRecord = new ExamRecord();
            examRecord.setStudentName(startExamVo.getStudentName());
            examRecord.setExamId(startExamVo.getPaperId());
            examRecord.setStatus("进行中");
            examRecord.setStartTime(LocalDateTime.now());
            baseMapper.insert(examRecord);
        }
        return examRecord;
    }

    @Override
    public ExamRecord getExamRecordDetailById(Integer id) {
        //调用自带的方法查询考试记录
        ExamRecord examRecord = baseMapper.selectById(id);
        //根据试卷id查询考试记录中的试卷信息
        Paper papersById = paperService.getPapersById(examRecord.getExamId());
        //将试卷设置到考试记录中
        examRecord.setPaper(papersById);
        //根据考试记录id查询用户的答题记录
        List<AnswerRecord> answerRecords = answerRecordMapper.selectList(new LambdaQueryWrapper<AnswerRecord>().eq(AnswerRecord::getExamRecordId, id));
        //设置用户的答题记录
        examRecord.setAnswerRecords(answerRecords);
        return examRecord;
    }

    @Override
    public void submitAnswers(Integer examRecordId, List<SubmitAnswerVo> answers) {
        //根据考试记录id查询考试记录
        ExamRecord examRecord = baseMapper.selectById(examRecordId);
        //设置考试结束时间
        examRecord.setEndTime(LocalDateTime.now());
        //设置考试状态为已完成
        examRecord.setStatus("已完成");
        //根据id更新考试记录（暂时先不更新了，等判卷之后统一更新）
        baseMapper.updateById(examRecord);
        //保存用户的答题记录
        //将List<SubmitAnswerVo>转换为List<ExamRecordAnswer>类型
        List<AnswerRecord> answerRecordStream = answers.stream().map(answer -> new AnswerRecord(examRecordId, answer.getQuestionId(), answer.getUserAnswer())).collect(Collectors.toList());
        //调用AnswerRecordService中的批量保存方法
        answerRecordSercive.saveBatch(answerRecordStream);
        //调用判卷的方法
        gradePager(examRecordId);
    }



    private void gradePager(Integer examRecordId) {
        ExamRecord examRecordDetailById = getExamRecordDetailById(examRecordId);
        List<Question> questions = examRecordDetailById.getPaper().getQuestions();
        Map<Long, Question> questionMap = questions.stream().collect(Collectors.toMap(Question::getId, question -> question));
        List<AnswerRecord> answerRecords = examRecordDetailById.getAnswerRecords();
        AtomicInteger correctCount = new AtomicInteger();
        //遍历用户的答题记录
        answerRecords.forEach(answerRecord -> {
            //获取题目id
            Long questionId = answerRecord.getQuestionId();
            //根据题目id获取题目信息
            Question question = questionMap.get(questionId);
            //获取用户的答案
            String userAnswer = answerRecord.getUserAnswer();
            //对于非简答题，手动判断用户的答案是否正确
            if (!"TEXT".equals(question.getType())) {
                if ("JUDGE".equals(question.getType())) {
                    userAnswer = userAnswer.equals("T") ? "TRUE" : "FALSE";
                }
                if (userAnswer.equals(question.getAnswer().getAnswer())) {
                    //设置用户答题记录中的得分为该题目在试卷中的分数
                    answerRecord.setScore(question.getPaperScore().intValue());
                    //设置用户答题记录中该题回答正确
                    answerRecord.setIsCorrect(1);
                    //对答对数量加1
                    correctCount.set(correctCount.get() + 1);
                } else {
                    answerRecord.setScore(0);
                    answerRecord.setIsCorrect(0);
                }
            } else {
                GradingResult gradingResult = aiService.gradeTextQuestions(question, userAnswer);
                Integer score = gradingResult.getScore();
                answerRecord.setScore(score);
                //判断简答题是否答对，如果得了满分，将isCorrect设置为1，如果得0分，设置为0，其他设置为2
                if (score.equals(0)) {
                    answerRecord.setIsCorrect(0);
                    answerRecord.setAiCorrection(gradingResult.getReason());
                } else if (score.equals(question.getPaperScore().intValue())) {
                    answerRecord.setIsCorrect(1);
                    answerRecord.setAiCorrection(gradingResult.getFeedback());
                    correctCount.set(correctCount.get() + 1);
                }else {
                    answerRecord.setIsCorrect(2);
                    answerRecord.setAiCorrection(gradingResult.getReason());
                    correctCount.set(correctCount.get() + 1);
                }
            }
            answerRecordMapper.updateById(answerRecord);
        });
        //获取当前试卷所有题目的总分
        int totalPaperScore = questions.stream().mapToInt(question -> question.getPaperScore().intValue()).sum();
        //计算用户的总得分
        int totalScore = answerRecords.stream().filter(answerRecord -> answerRecord.getIsCorrect() != 0).mapToInt(AnswerRecord::getScore).sum();
        //设置当前试卷的总分数
        examRecordDetailById.setScore(totalScore);
        examRecordDetailById.setStatus("已批阅");
        //调用AI获取考试评语
        String answer = aiService.getExamAnswer(totalScore,totalPaperScore,questionMap.size(),correctCount);
        examRecordDetailById.setAnswers(answer);
        baseMapper.updateById(examRecordDetailById);
    }

    @Override
    public void deleteExamRecord(Integer id) {
        boolean exists = baseMapper.exists(new LambdaQueryWrapper<ExamRecord>().eq(ExamRecord::getStatus, "进行中"));
        if (exists){
            throw new ExamException(999,"考试正在进行中，不能删除考试记录");
        }
        baseMapper.deleteById(id);
        answerRecordMapper.delete(new LambdaQueryWrapper<AnswerRecord>().eq(AnswerRecord::getExamRecordId,id));
    }

    @Override
    public List<ExamRankingVO> getExamRanking(Integer paperId, Integer limit) {

        return baseMapper.getExamRanking(paperId,limit);
    }
}